package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClientl;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0).map(menu -> {
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->menu1.getSort()-menu2.getSort()).collect(Collectors.toList());

        return level1Menus;
    }
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
//                    if(categoryEntity.getChildren()!=null){
                        categoryEntity.setChildren(getChildrens(categoryEntity, all));
//                    }
            return categoryEntity;
        }).sorted((menu1, menu2) -> (menu1.getSort()==null?0:menu1.getSort()) -(menu2.getSort()==null?0:menu2.getSort())).collect(Collectors.toList());
        return children;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }
    private List<CategoryEntity> getCategoryEntities(List<CategoryEntity> entityList, Long parent_cid) {

        return entityList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
    }
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        ArrayList<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }
    private List<Long> findParentPath(Long catelogId, ArrayList<Long> paths){
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }
    @Transactional
    @Caching(evict = {@CacheEvict(value = "category",key ="'level1Categorys'"),
                      @CacheEvict(value = "category",key ="'getCatelogJson'")})


    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
        categoryBrandRelationEntity.setCatelogId(category.getCatId());
        categoryBrandRelationEntity.setCatelogName(category.getName());
        categoryBrandRelationService.update(categoryBrandRelationEntity,new UpdateWrapper<CategoryBrandRelationEntity>().lambda().eq(CategoryBrandRelationEntity::getCatelogId,categoryBrandRelationEntity.getCatelogId()));
    }


    @Cacheable(value = "category",key = "'level1Categorys'")
    @Override
    public List<CategoryEntity> getLevel1Categirys() {
        System.out.println("调用了 getLevel1Categorys  查询了数据库........【一级分类】");
        List<CategoryEntity> list = this.list(new LambdaQueryWrapper<CategoryEntity>().eq(CategoryEntity::getParentCid, 0));
        return list;
    }
    private Map<String, List<Catelog2Vo>> getCatelogJsonFromDb() {
        String catelogJSON = redisTemplate.opsForValue().get("catelogJSON");
        if (!StringUtils.isEmpty(catelogJSON)) {
            System.out.println("缓存命中，查询redis");
            return JSON.parseObject(catelogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {});
        }
        System.out.println("缓存不命中，查询mysql");

        // 优化：将查询变为一次
        List<CategoryEntity> list = this.list();
        List<CategoryEntity> level1Categirys = getList(list,0L);
        Map<String, List<Catelog2Vo>> categoryEntities = level1Categirys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntityList = getList(list,v.getCatId());
            List<Catelog2Vo> Catelog2Vos = null;
            if (categoryEntityList != null) {
                Catelog2Vos = categoryEntityList.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<CategoryEntity> levle3Catelog = getList(list,l2.getCatId());
                    if (levle3Catelog!=null){
                        List<Catelog2Vo.Catelog3Vo> Catelog3VoList = levle3Catelog.stream().map(l3 -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(),l3.getCatId().toString(),l3.getName());
                                    return catelog3Vo;
                                }
                        ).collect(Collectors.toList());
                        catelog2Vo.setCatelog3List(Catelog3VoList);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return Catelog2Vos;
        }));
        redisTemplate.opsForValue().set("catelogJSON", JSON.toJSONString(categoryEntities), 1, TimeUnit.DAYS);
        return categoryEntities;
    }
    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        List<CategoryEntity> list = this.list();
        List<CategoryEntity> level1Categirys = getList(list,0L);
        Map<String, List<Catelog2Vo>> categoryEntities = level1Categirys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntityList = getList(list,v.getCatId());
            List<Catelog2Vo> Catelog2Vos = null;
            if (categoryEntityList != null) {
                Catelog2Vos = categoryEntityList.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<CategoryEntity> levle3Catelog = getList(list,l2.getCatId());
                    if (levle3Catelog!=null){
                        List<Catelog2Vo.Catelog3Vo> Catelog3VoList = levle3Catelog.stream().map(l3 -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(),l3.getCatId().toString(),l3.getName());
                                    return catelog3Vo;
                                }
                        ).collect(Collectors.toList());
                        catelog2Vo.setCatelog3List(Catelog3VoList);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return Catelog2Vos;
        }));
        return categoryEntities;
    }
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock",uuid,300,TimeUnit.SECONDS);
        if (lock) {
            Map<String, List<Catelog2Vo>> catelogJson;
            try {
                catelogJson = getCatelogJsonFromDb();
            } finally {
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return catelogJson;
        }else {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
            }
            return getCatelogJsonFromDbWithRedisLock();
        }

    }
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedissonLock() {
        RLock catelogJsonLock = redissonClientl.getLock("CatelogJson-lock");
        catelogJsonLock.lock();
        Map<String, List<Catelog2Vo>> catelogJson;
            try {
                catelogJson = getCatelogJsonFromDb();
            } finally {
                catelogJsonLock.unlock();
            }
            return catelogJson;
    }
//    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDb() {
//        List<CategoryEntity> list = this.list();
//        List<CategoryEntity> level1Categirys = getList(list,0L);
//        Map<String, List<Catelog2Vo>> categoryEntities = level1Categirys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
//            List<CategoryEntity> categoryEntityList = getList(list,v.getCatId());
//            List<Catelog2Vo> Catelog2Vos = null;
//            if (categoryEntityList != null) {
//                Catelog2Vos = categoryEntityList.stream().map(l2 -> {
//                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
//                    List<CategoryEntity> levle3Catelog = getList(list,l2.getCatId());
//                    if (levle3Catelog!=null){
//                        List<Catelog2Vo.Catelog3Vo> Catelog3VoList = levle3Catelog.stream().map(l3 -> {
//                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(),l3.getCatId().toString(),l3.getName());
//                                    return catelog3Vo;
//                                }
//                        ).collect(Collectors.toList());
//                        catelog2Vo.setCatelog3List(Catelog3VoList);
//                    }
//                    return catelog2Vo;
//                }).collect(Collectors.toList());
//            }
//            return Catelog2Vos;
//        }));
//        return categoryEntities;
//    }

    private List<CategoryEntity> getList(List<CategoryEntity> list,Long parent_cid) {
        List<CategoryEntity> collect = list.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

}
